﻿using Microsoft.AspNetCore.Mvc.Filters;
using System;

namespace EventBusNet6;

public class ExceptionFilter : IExceptionFilter, IAsyncExceptionFilter
{
    private readonly IWebHostEnvironment _env;
    private readonly ILogger<ExceptionFilter> _logger;
    public ExceptionFilter(IWebHostEnvironment env, ILogger<ExceptionFilter> logger)
    {
        _env = env;
        _logger = logger;
    }
    public void OnException(ExceptionContext context)
    {
        string message;
        if (_env.IsProduction())
        {
            message = "转换失败";
        }
        else
        {
            message = context.Exception.Message;
        }
        _logger.LogError(context.Exception, "");
        var data = FormatterResult.Failed(message,500);
        context.Result = new InternalServerErrorResult(data);
    }

    public Task OnExceptionAsync(ExceptionContext context)
    {
        OnException(context);
        return Task.CompletedTask;
    }
}
public class InternalServerErrorResult : ObjectResult
{
    public InternalServerErrorResult(object value) : base(value)
    {
        StatusCode = Microsoft.AspNetCore.Http.StatusCodes.Status500InternalServerError;
    }
}
